package Class.Handler;

import Class.Handler.*;
import Class.Dialog.*;
import Class.TextWindow.*;
import Class.Main.*;
import org.apache.commons.lang3.*;
import org.apache.commons.io.*;


import java.awt.*;
import java.lang.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class MenuHandler implements ActionListener {

    private TextWindow textWindow;

    public MenuHandler(TextWindow textWindow){
        this.textWindow = textWindow;
    }

    public void actionPerformed(ActionEvent e){
        String actionCommand = e.getActionCommand();
        System.out.println("actionCommand = "+ actionCommand);
        if("newBuild".equals(actionCommand)){
            processNewBuildItem();
        } else if ("open".equals(actionCommand)) {
            processOpenItem();
        } else if ("save".equals(actionCommand)) {
            doSave();
        } else if ("saveAs".equals(actionCommand)) {
            doSaveAS();
        } else if ("exit".equals(actionCommand)) {
            System.exit(0);
        } else if ("backout".equals(actionCommand)) {
            if(textWindow.getUndoManger().canUndo()){
                textWindow.getUndoManger().undo();  //已有现成撤回功能
            }
        } else if ("cut".equals(actionCommand)) {
            textWindow.getTextArea().cut(); //已有现成剪切功能
        } else if ("copy".equals(actionCommand)) {
            textWindow.getTextArea().copy();
        } else if ("stick".equals(actionCommand)) {
            textWindow.getTextArea().paste();
        } else if ("delete".equals(actionCommand)) {
            processDeleteItem();
        } else if ("find".equals(actionCommand))  {
            processFindItem();
        } else if ("alter".equals(actionCommand)) {
            processAlterItem();
        } else if ("turnTo".equals(actionCommand)) {
            processTurnToItem();
        } else if ("checkAll".equals(actionCommand)) {
            textWindow.getTextArea().selectAll();
        } else if ("timeAndDate".equals(actionCommand)) {
            processTimeAndDateItem();
        } else if ("autoAround".equals(actionCommand)) {
            boolean selected = textWindow.getAutoAround().isSelected();
            textWindow.getTextArea().setLineWrap(selected);//设置是否自动换行
        } else if ("typeFace".equals(actionCommand)) {
            processTypeFaceItem();
        } else if ("enlarge".equals(actionCommand)) {
            processEnlarge();
        } else if ("shrink".equals(actionCommand)) {
            processShrink();
        } else if ("defaultScaling".equals(actionCommand)) {
            processDefaultScaling();
        } else if ("statusBar".equals(actionCommand)) {
            textWindow.getStatusPanel().setVisible(textWindow.getStatusBar().isSelected());
        } else if ("checkHelp".equals(actionCommand)) {
            //URL=https://gitee.com/wanghao0122/text-book
            processCheckHelp();
        } else if ("aboutTextbook".equals(actionCommand)) {
            processAboutTextBook();
        } else if("deletePopup".equals(actionCommand)){
//            System.out.println(textWindow.getTextArea().getSelectedText());
            if(textWindow.getTextArea().getSelectedText() == null){
                return;
            }
            textWindow.getTextArea().replaceSelection("");
        }
    }

    private void processCheckHelp() {
        try {
            //String url = "http://www.baidu.com";
            String url = "https://gitee.com/wanghao0122/text-book";
            java.net.URI uri = java.net.URI.create(url);
            // 获取当前系统桌面扩展
            java.awt.Desktop dp = java.awt.Desktop.getDesktop();
            // 判断系统桌面是否支持要执行的功能
            if (dp.isSupported(java.awt.Desktop.Action.BROWSE)) {
                dp.browse(uri);// 获取系统默认浏览器打开链接
            }
        } catch (java.lang.NullPointerException e) {
            // 此为uri为空时抛出异常
            e.printStackTrace();
        } catch (java.io.IOException e) {
            // 此为无法获取系统默认浏览器
            e.printStackTrace();
        }
    }

    private void processAboutTextBook() {
        new AboutTextBookDialog(textWindow);
    }

    private void processDefaultScaling() {
        Font font = textWindow.getTextArea().getFont();
        Font newFont = new Font(font.getFamily(),font.getStyle(),textWindow.getDefaultFontSize());
        textWindow.getTextArea().setFont(newFont);
    }

    private void processShrink() {
        Font font = textWindow.getTextArea().getFont();
        Font newFont = new Font(font.getFamily(),font.getStyle(),font.getSize()-1);
        textWindow.getTextArea().setFont(newFont);
    }

    private void processEnlarge() {
        Font font = textWindow.getTextArea().getFont();
        Font newFont = new Font(font.getFamily(),font.getStyle(),font.getSize()+1);
        textWindow.getTextArea().setFont(newFont);
    }

    private void processTypeFaceItem() {
        new TypeFaceDialog(textWindow);
    }

    private void processTimeAndDateItem(){
        LocalDateTime now = LocalDateTime.now();
        String nowStr = now.format(DateTimeFormatter.ofPattern("HH:mm:ss yyyy-MM-dd"));
        int caretPosition = textWindow.getTextArea().getCaretPosition();
        textWindow.getTextArea().insert(nowStr,caretPosition);
    }

    private void processTurnToItem() {
        new TurnToDialog(textWindow);
    }

    private void processAlterItem() {
        new AlterDialog(textWindow);
    }

    private void processFindItem(){
        new FindDialog(textWindow);
    }

    private void processDeleteItem(){
    //方法思路：先获得光标位置，将光标位置移前，获得字符，将字符换成空
        //补充选中内容删除
        if(textWindow.getTextArea().getSelectedText() != null){
            textWindow.getTextArea().replaceSelection("");
            return;
        }
        //获取光标位置(指光标前面所有的字符的个数，包括换行符)
        int caretPosition = textWindow.getTextArea().getCaretPosition();
        if(caretPosition == 0){
            return;
        }
        textWindow.getTextArea().replaceRange("",caretPosition-1,caretPosition);
    }

    private void doSaveAS(){
        String filePath = textWindow.getFilePath();
        String title = textWindow.getTitle();
        JFileChooser jFileChooser = new JFileChooser();
        //弹出文件保存对话框
        int saveOption = jFileChooser.showSaveDialog(textWindow);
        if (saveOption == jFileChooser.APPROVE_OPTION) {
            //点击保存按钮
            File selectedFile = jFileChooser.getSelectedFile(); //返回保存的文件对象
            filePath = selectedFile.getAbsolutePath();
            title = selectedFile.getName();
            textWindow.setFilePath(filePath);
            textWindow.setTitle(title);
        } else {
            //点击取消按钮
        }
        textWindow.setHasSaved(true);
        try {
            //将内容写入磁盘
            FileUtils.writeStringToFile(new File(filePath), textWindow.getTextArea().getText(), StandardCharsets.UTF_8);
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    private void doSave() {
        String filePath = textWindow.getFilePath();
        String title = textWindow.getTitle();
        if (StringUtils.isBlank(filePath)) {
            //此时文件还没有被保存到磁盘上
            JFileChooser jFileChooser = new JFileChooser();
            //弹出文件保存对话框
            int saveOption = jFileChooser.showSaveDialog(textWindow);
            if (saveOption == jFileChooser.APPROVE_OPTION) {
                //点击保存按钮
                File selectedFile = jFileChooser.getSelectedFile(); //返回保存的文件对象
                filePath = selectedFile.getAbsolutePath();
                title = selectedFile.getName();
                textWindow.setFilePath(filePath);
                textWindow.setTitle(title);
            } else {
                //点击取消按钮
            }
        } else {
            //文件已保存到磁盘上了,再次保存
            textWindow.setTitle(StringUtils.substringAfter(title,"*"));

        }
        textWindow.setHasSaved(true);
        try {
            //将内容写入磁盘
            FileUtils.writeStringToFile(new File(filePath), textWindow.getTextArea().getText(), StandardCharsets.UTF_8);
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    //刷新，创建新窗口
    private void reset(){
        textWindow.getTextArea().setText("");
//        Thread.sleep(500);
        textWindow.setHasSaved(true);
        textWindow.setFilePath(null);
        textWindow.setTitle("未命名文档.txt");
    }

    private void processNewBuildItem(){
        if(textWindow.isHasSaved()==true){
            reset();
        }else{
            //返回点了哪个按钮
            int i = JOptionPane.showConfirmDialog(textWindow,"是否保存","记事本-提示",JOptionPane.YES_NO_CANCEL_OPTION);
            if(i == JOptionPane.YES_OPTION){
                doSave();
                reset();
            } else if (i == JOptionPane.NO_OPTION) {
                reset();
            }
        }
    }

    private void processOpenItem(){
        JFileChooser jFileChooser = new JFileChooser();
        jFileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));//设置默认打开目录为用户界面目录
        //文件选择对话框
        int clickButton = jFileChooser.showOpenDialog(textWindow);
        if(clickButton == jFileChooser.APPROVE_OPTION){
            //点击了某个文件
            File selectedFile = jFileChooser.getSelectedFile();
            try{
                String fileContent = FileUtils.readFileToString(selectedFile,StandardCharsets.UTF_8);
                textWindow.getTextArea().setText(fileContent);
                textWindow.setTitle(selectedFile.getName());
                textWindow.setHasSaved(true);
                textWindow.setFilePath(selectedFile.getAbsolutePath());
            }catch (IOException e){
                e.printStackTrace();
            }
        }else{
            //点击取消
        }
    }

}